package me.chan.web;

import me.chan.entity.Data;
import me.chan.entity.Handler;
import me.chan.entity.Param;
import me.chan.entity.View;
import me.chan.helper.BeanHelper;
import me.chan.helper.ConfigHelper;
import me.chan.helper.ControllerHelper;
import me.chan.helper.LoaderHelper;
import me.chan.util.CodecUtil;
import me.chan.util.JsonUtil;
import me.chan.util.ReflectUtil;
import me.chan.util.StreamUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by JanGin on 2017/6/21.
 */
@WebServlet(urlPatterns = "/*",  loadOnStartup = 0)
public class DispatcherServlet extends HttpServlet{

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.service(req, resp);

        String requestMethod = req.getMethod().toLowerCase();
        String requestPath = req.getPathInfo();


        //TODO  continue to write the code here
        Handler handler = ControllerHelper.getHandler(requestMethod, requestPath);
        if (handler != null) {

            Class<?> controllerClass = handler.getControllerClass();
            //get the controller bean to handler the request
            Object controllerInstance = BeanHelper.getBean(controllerClass);

            //create the param object
            Map<String, Object> paramMap = new HashMap<>();
            Enumeration<String> parameterNames =  req.getParameterNames();
            while (parameterNames.hasMoreElements()) {
                String paramName = parameterNames.nextElement();
                String paramValue = req.getParameter(paramName);
                paramMap.put(paramName, paramValue);
            }

            String body = CodecUtil.decodeURL(StreamUtil.getString(req.getInputStream()));
            if (StringUtils.isNoneEmpty(body)) {
                String[] params = StringUtils.split(body, '&');
                if (ArrayUtils.isNotEmpty(params)) {
                    for (String param : params) {
                        String[] paramPair = StringUtils.split(param, '=');
                        if (ArrayUtils.isNotEmpty(paramPair) && paramPair.length == 2) {
                            String paramName = paramPair[0];
                            String paramValue = paramPair[1];
                            paramMap.put(paramName, paramValue);
                        }
                    }
                }
            }

            Param param = new Param(paramMap);
            //call the action method
            Method actionMethod = handler.getActionMethod();
            Object result = ReflectUtil.invokeMethod(controllerInstance, actionMethod, param);

            //return view type
            if (result instanceof View) {
                View v = (View) result;
                String viewPath = v.getViewPath();
                if (StringUtils.isNotEmpty(viewPath)) {
                    if (viewPath.startsWith("/")) {
                        resp.sendRedirect(req.getContextPath() + viewPath);
                    } else {
                        Map<String, Object> model = v.getModel();
                        for (Map.Entry<String, Object> entry : model.entrySet()) {
                            req.setAttribute(entry.getKey(), entry.getValue());
                        }
                        req.getRequestDispatcher(ConfigHelper.getAppJspPath() + viewPath).forward(req, resp);
                    }
                }
            }
            //return data type eg. JSON
            else if (result instanceof Data) {
                Data data = (Data) result;
                Object model = data.getModel();
                if (model != null) {
                    resp.setContentType("application/json");
                    resp.setCharacterEncoding("UTF-8");
                    PrintWriter writer  = resp.getWriter();
                    String jsonData = JsonUtil.toJson(model);
                    writer.write(jsonData);
                    writer.flush();
                    writer.close();
                }
            }
        }
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        //init all the helper classes
        LoaderHelper.init();
        ServletContext servletContext = getServletContext();

        //register the servlet to handle the jsp resources
        ServletRegistration jspSerlvet = servletContext.getServletRegistration("jsp");
        jspSerlvet.addMapping(ConfigHelper.getAppJspPath() + "*");

        //register the servlet to handle the static resource
        ServletRegistration staticServlet = servletContext.getServletRegistration("default");
        staticServlet.addMapping( ConfigHelper.getAppStaticPath() + "*");
    }
}
